package patternRecognition;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import recordProcessing.RecordParser;

import main.Main;

import data.DataMatcher;

import fields.FieldMatcher;
import fileProcessing.ParsingException;

public class QueryWithoutStructure extends PatternQuery implements Runnable{

	private String resultsFilePath;
	
	public QueryWithoutStructure(File f,String fileName) {
		super(f);
		resultsFilePath = fileName;
	}
	
	public void performAnalysis() throws ParsingException{
		analyzeFile();
		
		//What are the lengths of the lines, is there a pattern?
		/*If not search line by line for field-value pairs, also search just for field names
		 * and then search for just values.  Some records span fieldname-value pairs over two lines
		 * so it may be necessary to search the next line after a fieldname is identified.
		 */
		
		//place all words into one array
		int lineNumber=0,wordNumber=0;
		
		int sourceNum = (new File(resultsFilePath).list()).length;
		try {
			BufferedWriter searchResults = new BufferedWriter(new FileWriter(resultsFilePath+"\\Source"+sourceNum+"_search results.txt"));
			String dataMatcher;
			for(ArrayList<String> r : wordsByRow){
				lineNumber++;
				for(String s : r){
					wordNumber++;
					dataMatcher = new DataMatcher().matchesData(s);
					if(FieldMatcher.matchesField(s)){
						searchResults.write("("+lineNumber+","+wordNumber+")"+" Field Name Matched: "+s+"\r\n");
					}
					else if (dataMatcher != null){
						searchResults.write("("+lineNumber+","+wordNumber+")"+" Data Matched, "+ dataMatcher+": "+s+"\r\n");
					}
				}
			}
			searchResults.flush();
			searchResults.close();
		} catch (IOException e) {
			throw new ParsingException("Could not create QWS search results file.");
		}
	}

	@Override
	public void run() {
		try {
			performAnalysis();
			RecordParser.threadCount++;
		} catch (ParsingException e) {
			try {
				Main.audit.writeToAudit(e.getMessage());
			} catch (ParsingException e1) {
			}
		}
	}

//	private void getUserDefinition(ArrayList<String> r) {
//		// TODO Auto-generated method stub
//		
//	}
}
